package com.umpay.util;

import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeUtil {

    private static SimpleDateFormat yyyyDf = new SimpleDateFormat("yyyy");

    public static String date(String fmt) {
        return new SimpleDateFormat(fmt).format(new Date());
    }

    public static String date(String fmt, long t) {
        return new SimpleDateFormat(fmt).format(new Date(t));
    }

    public static String date8() {
        return new SimpleDateFormat("yyyyMMdd").format(new Date());
    }

    public static String date8(Date date) {
        return new SimpleDateFormat("yyyyMMdd").format(date);
    }

    public static String time6() {
        return new SimpleDateFormat("HHmmss").format(new Date());
    }

    public static String time6(Date date) {
        return new SimpleDateFormat("HHmmss").format(date);
    }

    public static String datetime14() {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
    }

    public static String datetime14(Date date) {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(date);
    }

    public static String datetime14(long t) {
        return new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(t));
    }

    public static String calcMonth(String month6, int m) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(month6.substring(0, 4)), Integer.parseInt(month6.substring(4, 6)) - 1, 1);
        cal.add(Calendar.MONTH, m);
        return new SimpleDateFormat("yyyyMM").format(cal.getTime());
    }

    public static String calcDay(String day8, int d) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        cal.add(Calendar.DATE, d);
        return new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
    }

    public static String calcSecond(String time14, int s) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(time14.substring(0, 4)), Integer.parseInt(time14.substring(4, 6)) - 1,
                Integer.parseInt(time14.substring(6, 8)), Integer.parseInt(time14.substring(8, 10)),
                Integer.parseInt(time14.substring(10, 12)), Integer.parseInt(time14.substring(12, 14)));
        cal.add(Calendar.SECOND, s);
        return new SimpleDateFormat("yyyyMMddHHmmss").format(cal.getTime());
    }

    public static long toMilliSec(String time14) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(time14.substring(0, 4)), Integer.parseInt(time14.substring(4, 6)) - 1,
                Integer.parseInt(time14.substring(6, 8)), Integer.parseInt(time14.substring(8, 10)),
                Integer.parseInt(time14.substring(10, 12)), Integer.parseInt(time14.substring(12, 14)));
        return cal.getTimeInMillis();
    }

    public static int getActualMaximum(String day8, int field) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        return cal.getActualMaximum(field);
    }

    public static int getActualMinimum(String day8, int field) {
        Calendar cal = Calendar.getInstance();
        cal.set(Integer.parseInt(day8.substring(0, 4)), Integer.parseInt(day8.substring(4, 6)) - 1,
                Integer.parseInt(day8.substring(6, 8)));
        return cal.getActualMinimum(field);
    }

    /**
     * 得到系统时间年份
     * 
     * @return
     */
    public static String getDateYear() {
        return yyyyDf.format(new Date());
    }

    /**
     * 处理银行的checkDate没有年份的情冄1�7
     * 
     * @param v
     * @return
     */
    public static String formatBankCheckDate(String v) {
        if (v.length() == 4) {
            String yyyy = getDateYear();
            String stldate = yyyy + v;
            try {
                SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");

                long slttime = fmt.parse(stldate).getTime();

                long currtime = System.currentTimeMillis();

                long dis = slttime - currtime;

                long day1 = 24 * 3600 * 1000;

                if (Math.abs(dis) >= day1) {

                    if (slttime < currtime) {

                        yyyy = String.valueOf(Integer.parseInt(yyyy) + 1);

                        stldate = yyyy + v;

                    } else {

                        yyyy = String.valueOf(Integer.parseInt(yyyy) - 1);

                        stldate = yyyy + v;

                    }

                }

                return stldate;
            } catch (Exception e) {

            }
        }
        return v;

    }

    /**
     * String
     * 
     * @param time
     * @return
     */
    public static String parseTimestampToDStr(Timestamp time) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        formatter.format(time);
        return formatter.format(time);
    }

    /**
     * String
     * 
     * @param time
     * @return
     */
    public static String parseTimestampToTStr(Timestamp time) {
        SimpleDateFormat formatter = new SimpleDateFormat("HHmmss");
        formatter.format(time);
        return formatter.format(time);
    }

    public static String formatDateTime(Date date) {
        return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(date);
    }

    /**
     * description: 在now基础上增加amount个日
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Date addDay(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.DATE, amount);
        return cal.getTime();
    }

    /**
     * description: 在now基础上增加amount个月
     * 
     * @param now
     * @param amount
     * @return
     */
    public static Date addMonth(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MONTH, amount);
        return cal.getTime();
    }

    /**
     * description: 在now基础上增加amount个年
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Date addYear(Date now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.YEAR, amount);
        return cal.getTime();
    }

    /**
     * description: 在now基础上增加amount个分钟
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static Timestamp addMin(Timestamp now, int amount) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.add(Calendar.MINUTE, amount);
        return new Timestamp(cal.getTime().getTime());
    }

    /**
     * 格式化日期为制定字符串
     * 
     * @param date
     * @param format
     * @return
     */
    public static String foramtDate2String(Date date, String format) {
        return new SimpleDateFormat(format).format(date);
    }

    /**
     * 将日期格式的字符串转换为日期
     * 
     * @param dateStr
     *            源日期字符串
     * @param formatStr
     *            源日期字符串格式
     */
    public static Date formatStringToDate(String dateStr, String formatStr) {
        SimpleDateFormat format = new SimpleDateFormat(formatStr);
        try {
            return format.parse(dateStr);
        } catch (Exception ex) {
            RuntimeException rex = new RuntimeException(ex.getMessage());
            rex.setStackTrace(ex.getStackTrace());
            throw rex;
        }
    }

    /**
     * description: 判断当前时间是否为19点以后
     * 
     * @param endDate
     * @param amount
     * @return
     */
    public static boolean nowIsNight() {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        int i = cal.get(Calendar.HOUR_OF_DAY);
        return i > 18;
    }

    /**
     * 获取数据库日期,如果获取失败则取系统当前日期 * @param format日期格式化字符串
     * 
     * @return
     */
    public static String getDbTime(String format) {
        SimpleDateFormat formatter = new SimpleDateFormat(format);
        Timestamp dbTime = null;
        String currTime = "";
        // try {
        // CommonDao commonDao = DaoFactory.getCommonDao();
        // dbTime = commonDao.getCurrentDBTime();
        // } catch (Exception e) {
        // dbTime = new Timestamp(System.currentTimeMillis());
        // }
        // if(dbTime == null){
        dbTime = new Timestamp(System.currentTimeMillis());
        // }
        currTime = formatter.format(dbTime);
        return currTime;
    }

    /**
     * 校验交易日期是否小于当前数据库日期指定天数
     * 
     * @param trace
     * @param day
     * @return
     */
    public static boolean checkTransDateByTrace(String trace, int day) {
        String traceDate = trace.substring(0, 6);
        return checkTransDate(traceDate, day, "yyMMdd");
    }

    /**
     * 校验日期是否小于当前数据库日期的指定天数
     * 
     * @param datestr
     *            需要验证的日期
     * @param day
     *            指定天数
     * @param patt
     *            日期格式,例:yyyyMMdd
     * @return
     */
    public static boolean checkTransDate(String datestr, int day, String patt) {
        SimpleDateFormat format = new SimpleDateFormat(patt);
        try {
            Date date = format.parse(datestr);
            Date dbDate = format.parse(getDbTime(patt));
            return addDay(date, day).getTime() < dbDate.getTime();
        } catch (ParseException e) {
            return false;
        }
    }

    /**

     * 计算两个日期相差的月数
     * @author: lile
     * @create: 2019-03-20 13:52
     * @param date1 起始日期
     * @param date2 结束日期
     * @param pattern 日期格式
     * @return 相差月数，返回结果0,
     * + 结束日期大于起始日期
     * - 结束日期小于起始日期
     * @throws ParseException
     */
    public static int getMonthSpace(String date1, String date2,String pattern)
            throws ParseException {
//        int result = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(sdf.parse(date1));
        c2.setTime(sdf.parse(date2));
        int year =c2.get(Calendar.YEAR)-c1.get(Calendar.YEAR);
//        result = c2.get(Calendar.MONTH) - c1.get(Calendar.MONTH);
//        if(year<0){
////            year=-year;
//            return year*12+c1.get(Calendar.MONTH)-c2.get(Calendar.MONTH);
//        }
        return year*12+c2.get(Calendar.MONTH)-c1.get(Calendar.MONTH);
    }


    public static boolean beforeNow(String date1, String pattern)
            throws ParseException {
//        int result = 0;
        SimpleDateFormat sdf = new SimpleDateFormat(pattern);
        Calendar c1 = Calendar.getInstance();
        Calendar c2 = Calendar.getInstance();
        c1.setTime(sdf.parse(date1));
//        if(year<0){
////            year=-year;
//            return year*12+c1.get(Calendar.MONTH)-c2.get(Calendar.MONTH);
//        }
        return c1.getTime().before(c2.getTime());
    }


    public static void main(String[] args) throws ParseException {
        System.out.println(getMonthSpace("20171001","20180302","yyyyMMdd"));
        System.out.println(beforeNow("20170321","yyyyMMdd"));
    }
    /**
     * 获取指定日期之前一周一个月或者三个月的日期
     * 
     * @param dateFlag
     *            日期标识
     * @param endDate
     *            指定日期
     * @return
     */
    public static String dateSub(String dateFlag , String endDate) {
    	SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
    	Calendar calendar = Calendar.getInstance();
    	try {
			calendar.setTime(df.parse(endDate));
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	if("week".equals(dateFlag)) {
    		calendar.add(Calendar.DATE, -7);
    	}else if("month".equals(dateFlag)) {
    		calendar.add(Calendar.MONTH, -1);
    	}else if("weekAdd".equals(dateFlag)) {
    		calendar.add(Calendar.DATE, 6);
    	}else {
    		calendar.add(Calendar.MONTH, -3);
    	}
    	
    	String retVal = df.format(calendar.getTime());
    	return retVal;
	}

}
